<?php

class CultivationResearchService
{

    /**
     * @var CultivationResearchService
     */
    private static $instance;

    /**
     * Get the instance of CultivationResearchService.
     *
     * @return CultivationResearchService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new CultivationResearchService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {

    }

    /**
     * 获取培育研究数据
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getSituation($userId,$reqTime)
    {
        //获取配置数据
        $lotteryConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_CULTIVATE, null, true);
        if (!$lotteryConf){
            throw new SzException(29037); //配置不存在
        }
        $changeCd = $lotteryConf[1]['refresh'];
        /** @var CultivationResearchVo $researchInfo */
        //获取玩家研究数据
        $researchInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_CULTIVATION_RESEARCH);
        $researchSituation = array();
        if ($researchInfo) {
            $newItemArr = $lotteryConf[1]['cultivateProp'];
            $newItemId = $newItemArr[array_rand($newItemArr)];
            //验证是否需要更新培育材料
            $changeTime = $researchInfo->getChangeTime();
            $coodTime = $researchInfo->getCoolingTime();
            $isReward = $researchInfo->getIsReward();

            if ($changeTime <= $reqTime) {
                $researchInfo->setItemId($newItemId);
                $researchInfo->setSubmitNum(0);
                $researchInfo->setChangeTime($reqTime + $changeCd);
            }

            if ($coodTime <= $reqTime && $coodTime !=0 && $isReward !=1){
                $researchInfo->setItemId($newItemId);
                $researchInfo->setSubmitNum(0);
                $researchInfo->setChangeTime($reqTime + $changeCd);
                $researchInfo->setCoolingTime(0);
                $researchInfo->setFlowerId(0);
                $researchInfo->setFlowerNum(0);
                $researchInfo->setIsReward(0);
            }

            $researchSituation = $researchInfo->toArray();
//            if ($isReward == 0 &&  $changeTime < $reqTime ||
//                $isReward == 2 &&  $coodTime <= $reqTime
//            ){
//                $newItemArr = $lotteryConf[1]['cultivateProp'];
//                //随机获取数组中的任一道具ID
//                $newItemId = $newItemArr[array_rand($newItemArr)];
//                $researchInfo->setItemId($newItemId);
//                $researchInfo->setLuckNum(0);
//                $researchInfo->setSubmitNum(0);
//                $researchInfo->setChangeTime($reqTime + $changeCd);
//                $researchInfo->setCoolingTime(0);
//                $researchInfo->setFlowerId(0);
//                $researchInfo->setFlowerNum(0);
//                $researchInfo->setIsReward(0);
//            }
        }
        else{
            $itemArr = $lotteryConf[1]['cultivateProp'];
            //随机获取数组中的任一道具ID
            $itemId = $itemArr[array_rand($itemArr)];
            if (!empty($itemId)){
                //创建新的数据
                $researchInfo = new CultivationResearchVo(
                    $userId, // userId
                    0, //luckNum
                    $itemId, // itemId
                    0, // submitNum
                    $reqTime+$changeCd,//changeTime
                    0,//coolingTime
                    0,
                    0,
                    0,
                    true
                );
            }

            $researchSituation = array(
                'userId'        =>  $userId,
                'luckNum'       =>  0,
                'itemId'        =>  $itemId,
                'submitNum'     =>  0,
                'changeTime'    =>  $reqTime+$changeCd,
                'coolingTime'   =>  0,
                'flowerId'      =>  0,
                'flowerNum'     =>  0,
                'isReward'      =>  0

            );
        }

        //更新数据
        SzPersister::get()->setVo($researchInfo);

        return $researchSituation;
    }


    /**
     * 研究开始
     * @param $userId
     * @param $subNum
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function startResearch($userId,$subNum,$reqTime)
    {
        /** @var  CultivationResearchVo $researchInfo*/
        $researchInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_CULTIVATION_RESEARCH);
        if (!$researchInfo){
            throw new SzException(29035); //请先进行提交培育材料
        }
        if ($researchInfo->getCoolingTime() > $reqTime){
            throw new SzException(29036); //正在研制过程中
        }
        //获取配置文件
        $lotteryConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_CULTIVATE, null, true);
        if (!$lotteryConf){
            throw new SzException(29037); //配置不存在
        }
        $coolCd = $lotteryConf[1]['researchCd'];
        $totalNum = $researchInfo->getLuckNum() + $subNum;
        $lotteryQuantityConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_QUANTITY, $subNum, true);
        $count = 0;
        $totalNumLast = 0;
        if ($researchInfo->getLuckNum() >= $lotteryConf[1]['luckyValue']){
            $totalNumLast = $totalNum - $lotteryConf[1]['luckyValue'];
            $lotteryQuantityConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_QUANTITY, $subNum, true);
            $count = $lotteryQuantityConf['quantity'][1];
            $useNum = $subNum;
        }else{
            if ($totalNum >= $lotteryConf[1]['luckyValue']){
                $lotteryQuantityConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_QUANTITY, $subNum, true);
                $count = rand($lotteryQuantityConf['quantity'][0],$lotteryQuantityConf['quantity'][1]);
                $totalNumLast = $totalNum;
            }else{
                $count = rand($lotteryQuantityConf['quantity'][0],$lotteryQuantityConf['quantity'][1]);
                $totalNumLast = $totalNum;
                $useNum = $subNum;
            }
        }

//        if ($totalNum >= $lotteryConf[1]['luckyValue']){
//            $useNum = $lotteryConf[1]['luckyValue'] - $researchInfo->getLuckNum();
//            $lotteryQuantityConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_QUANTITY, $useNum, true);
//            $count = $lotteryQuantityConf['quantity'][1];
//            $totalNumLast = $lotteryConf[1]['luckyValue'];
//        }else{
//            $count = rand($lotteryQuantityConf['quantity'][0],$lotteryQuantityConf['quantity'][1]);
//            $totalNumLast = $totalNum;
//            $useNum = $subNum;
//        }

        $itemId = $researchInfo->getItemId();
        //扣除道具
        $entityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_CONSUME, GameConst::ENTITY_TYPE_ITEM, $itemId);
        GameService::get()->handleEntity($userId, $entityId, $subNum, true);
        CommonFunctionService::get()->reportResourceUseDetails(17000075,$userId,0,$entityId.':'.$subNum.'|','startResearch');//消耗资源上报

        //获取玩家已有鲜花id
        /**
         * @var $seedList PlantSeedVoList
         */
        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_PLANT_SEED)->toArray();
        //随机获取数组中的任一道具ID
        $flowerId = array_rand($seedList);
        $researchInfo->setSubmitNum($subNum);
        $researchInfo->setLuckNum($totalNumLast);
        $researchInfo->setCoolingTime($reqTime + $coolCd);
        $researchInfo->setFlowerId($flowerId);
        $researchInfo->setFlowerNum($count);
        $researchInfo->setIsReward(1);
        //更新数据
        SzPersister::get()->setVo($researchInfo);

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_9, $reqTime,1);

        return array(
            'userId'        =>  $userId,
            'luckNum'       =>  $totalNumLast,
            'itemId'        =>  $itemId,
            'submitNum'     =>  $useNum,
            'changeTime'    =>  $researchInfo->getChangeTime(),
            'coolingTime'   =>  $reqTime + $coolCd,
            'flowerId'      =>  $flowerId,
            'flowerNum'     =>  $count,
            'isReward'     =>   1,
        );
    }

    /**
     * 购买冷却时间
     * @param $userId
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function clearCoolTime($userId,$reqTime)
    {
        /** @var CultivationResearchVo $researchInfo */
        $researchInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_CULTIVATION_RESEARCH);
        if (!$researchInfo){
            throw new SzException(29035); //请先进行提交培育材料
        }

        //获取冷却时间
        $needClear = $researchInfo->getCoolingTime() - $reqTime;
        if ($needClear <= 0){
            throw new SzException(29038);//已经完成培育
        }
        $config = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'CultivatingTime', true);
        list($min,$val) = explode(',',$config['value']);
        $count = ceil($needClear / 60 / $min) * $val;
        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $count, true);
        CommonFunctionService::get()->reportResourceUseDetails(17000075,$userId,0,GameConst::ENTITY_ACTION_CONSUME_MONEY.':'.$count.'|','clearCoolTime');//消耗资源上报


        $researchInfo->setCoolingTime($reqTime);
        //更新数据
        SzPersister::get()->setVo($researchInfo);

        return true;
    }

    /**
     * 获得研究奖励
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function getReward($userId,$reqTime)
    {
        /** @var CultivationResearchVo $researchInfo */
        $researchInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_CULTIVATION_RESEARCH);
        if (!$researchInfo){
            throw new SzException(29035); //请先进行提交培育材料
        }
        if ($researchInfo->getIsReward() != 1){
            throw new SzException(29036,$reqTime);
        }

        //获取配置文件
        $lotteryConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_LOTTERY_CULTIVATE, null, true);
//        $flowerConf = SzConfig::get()->loadAppConfig(GameConst::ft_exclusive_flower, null, true);
        if (!$lotteryConf){
            throw new SzException(29037); //配置不存在
        }
        $flowerId = $researchInfo->getFlowerId();
        $count = $researchInfo->getFlowerNum();
        $entityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_GET, GameConst::ENTITY_TYPE_ITEM, $flowerId);
        GameService::get()->handleEntity($userId,$entityId, $count, true);
        CommonFunctionService::get()->reportResourceUseDetails(17000075,$userId,1,$entityId.':'.$count.'|','getReward');//消耗资源上报

        $researchInfo->setIsReward(2);

        //更新数据
        SzPersister::get()->setVo($researchInfo);

        return array(
            'isReward'      =>  2
        );
    }

}